package com.leyou.auth.web;

import com.leyou.auth.service.AuthService;
import com.leyou.common.auth.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     * @param username  用户名
     * @param password  用户密码
     * @param response  HttpResqonse
     */
    @PostMapping("/login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletResponse response
    ){
        authService.login(username,password,response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 验证token, 并返回token中的用户信息
     * @param request   cookie所在请求
     * @param response  cookie所在响应
     * @return  返回token中载荷对象UserInfo
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verifyUser(
            HttpServletRequest request,
            HttpServletResponse response
    ){
        UserInfo userInfo = authService.verifyUser(request,response);
        return ResponseEntity.ok(userInfo);
    }


    /**
     * 用户退出
     * @param request   请求(获取cookie)
     * @param response  响应(删除cookie)
     * @return
     */
    @PostMapping("/logout")
    public ResponseEntity<Void> logout(
            HttpServletRequest request,
            HttpServletResponse response
    ){
        authService.logout(request,response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 微服务的授权功能
     * @param id       服务id
     * @param secret   服务密码
     * @return         给服务签发的token(JWT)
     */
    @GetMapping("/authorization")
    public ResponseEntity<String> authorize(
            @RequestParam("id") Long id,
            @RequestParam("secret") String secret
    ){
        String token = authService.authorize(id, secret);
        return ResponseEntity.ok(token);
    }



}
